package com.vincent.program;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class HotelUtil {

	public static String findTheCheapest(String inputString) {
		String[] params = inputString.trim().split("\\s+");
		return findTheCheapest(params[0],
				Arrays.copyOfRange(params, 1, params.length));
	}

	public static String findTheCheapest(String userType, String... dateStrings) {
		Hotel lakewood = Hotel.lakewood();
		Hotel bridgewood = Hotel.bridgewood();
		Hotel ridgewood = Hotel.ridgewood();
		Hotel cheapestHotel = null;
		double cheapestPrice = 0d;

		List<PriceType> types = getPriceTypes(userType, dateStrings);
		double totalPriceOfLakewood = lakewood.calculateFee(types);
		double totalPriceOfBridgewood = bridgewood.calculateFee(types);
		double totalPriceOfRidgewood = ridgewood.calculateFee(types);
		cheapestPrice = Math.min(
				Math.min(totalPriceOfLakewood, totalPriceOfBridgewood),
				totalPriceOfRidgewood);

		if (cheapestPrice == totalPriceOfLakewood) {
			cheapestHotel = lakewood;
		}
		if (cheapestPrice == totalPriceOfBridgewood) {
			cheapestHotel = findTheHighestRateHotel(cheapestHotel, bridgewood);
		}
		if (cheapestPrice == totalPriceOfRidgewood) {
			cheapestHotel = findTheHighestRateHotel(cheapestHotel, ridgewood);
		}
		return cheapestHotel.getName();
	}

	private static List<PriceType> getPriceTypes(String userType,
			String[] dateStrings) {
		List<PriceType> types = new ArrayList<PriceType>();
		for (String dateStr : dateStrings) {
			types.add(new PriceType(userType, getDayType(dateStr)));
		}
		return types;
	}

	private static String getDayType(String dateStr) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = df.parse(dateStr);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int today = cal.get(Calendar.DAY_OF_WEEK);
		if (today >= Calendar.MONDAY && today <= Calendar.FRIDAY)
			return PriceType.WEEKDAY;
		return PriceType.WEEKEND;
	}

	private static Hotel findTheHighestRateHotel(Hotel a1, Hotel a2) {
		if (null != a1 && null != a2) {
			return a1.getRate() > a2.getRate() ? a1 : a2;
		}
		return null == a1 ? a2 : a1;

	}
}
